package com.seeyon.ctp.rest.resources;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;

import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.manager.FormDataBaseManager;
import com.seeyon.apps.kk.util.HeheHttpUtil;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormAuthViewBean;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormDataSubBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.form.po.FormModuleAuth;
import com.seeyon.ctp.util.DateUtil;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.ParamUtil;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.annotation.RestInterfaceAnnotation;
import com.seeyon.ctp.util.json.JSONUtil;

@Path("cap4/qiangs")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class MultipleSelectResources  extends BaseResource {
    private static final Log LOG = CtpLogFactory.getLog(OcrCustomResource.class);
    private EnumManager enumManagerNew = (EnumManager) AppContext.getBean("enumManagerNew");
    private FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
    private FormDataBaseManager kkBaseFormManager = (FormDataBaseManager) AppContext.getBean("kkBaseFormManager");;

    
    /**
     * 显示枚举名称
     * @param flowNo
     * @return
     */
    @GET
    @Path("enumShowValue")
    @RestInterfaceAnnotation(OpenExternal = RestInterfaceAnnotation.External.NO, StartVersion = "V7.0")
    public Response EnumShowValue(@QueryParam("flowNo") String flowNo) {
    	String ret = "";
		for(String id : flowNo.split(",")){
			try {
				if(Strings.isEmpty(ret)){
					ret = enumManagerNew.getCtpEnumItem(Long.valueOf(id)).getShowvalue();
				} else {
					ret += "," + enumManagerNew.getCtpEnumItem(Long.valueOf(id)).getShowvalue();
				}
			} catch (NumberFormatException | BusinessException e) {
				// TODO Auto-generated catch block
				LOG.error("##强生客开: id=" + id + "获取枚举名称异常", e);
			}
		}
        if (StringUtils.isNotBlank(ret)) {
            return success(ret);
        } else {
            return success("error");
        }
    }
    
    /**
	 * 获取关键人底表表权限
	 * @return
	 */
    @GET
    @Path("memberUpdateAuth")
    @RestInterfaceAnnotation(OpenExternal = RestInterfaceAnnotation.External.NO, StartVersion = "V7.0")
    public Response findKeyMemberUpdatAuth() {
        try {
            String auth = "";
            FormBean keyBean = formApi4Cap4.getFormByFormCode(Constants.keyMemberCode);
            List<FormModuleAuth> moduleList = keyBean.getAllModuleAuthList();
            for (FormModuleAuth module : moduleList) {
                auth = module.getModuleId().toString() + "|";
                break;
            }
            if (Strings.isEmpty(auth)) {
            	return success(null);
            }
            List<FormAuthViewBean> authViewLink = keyBean.getAllFormAuthViewBeans();
            for (FormAuthViewBean view : authViewLink) {
                if ("update".equals(view.getType())) {
                    auth += view.getFormViewId() + "." + view.getId();
                    break;
                }
            }

            if (Strings.isEmpty(auth)) {
            	return success(null);
            } else {
            	return success(auth);
            }
        } catch (BusinessException e) {
            // TODO Auto-generated catch block
            LOG.error("##强生客开: ", e);
        }
        return success(null);
    }

    @GET
    @Path("isReport")
    @RestInterfaceAnnotation(OpenExternal = RestInterfaceAnnotation.External.NO, StartVersion = "V7.0")
    public Response isReport(@QueryParam("flowNo") String flowNo) {
        try {
            FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
            FormBean formBean = formApi4Cap4.getFormByFormCode(Constants.hehe);
            FlipInfo fli = new FlipInfo(1, 20);
            Map<String, Object> where = new HashMap<String, Object>();
            where.put(formBean.getFieldBeanByDisplay("流水号").getName(), flowNo);//经销商ID
            List<FormDataMasterBean> list = formApi4Cap4.findMasterDataList(fli, formBean.getId(), null, where);
            if (CollectionUtils.isEmpty(list)) {
                return success("error");
            } else {
                return success("ok");
            }
        } catch (BusinessException e) {
            // TODO Auto-generated catch block
            LOG.error("##强生客开: ", e);
            return success("error");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            LOG.error("##强生客开: ", e);
            return success("error");
        }
    }

    @GET
    @Path("generateReport")
    @RestInterfaceAnnotation(OpenExternal = RestInterfaceAnnotation.External.NO, StartVersion = "V7.0")
    public Response generateReport(@QueryParam("form") String form, 
    			@QueryParam("formmain") String formmain) {
        Long formId = Long.valueOf(form);
        Long formmainId = Long.valueOf(formmain);
        try {
            FormBean formBean = formApi4Cap4.getForm(formId);
            FormDataMasterBean data = formApi4Cap4.findDataById(formmainId, formId, null);
            Map reportMap = data2ReportMap(data, formBean);
            LOG.info("********************************");
            LOG.info("向启信宝推送报告信息为： "+JSONUtil.toJSONString(reportMap));
            LOG.info("********************************");
            String agentName = getString(data, formBean, "经销商名称");
            Map res = HeheHttpUtil.generateReportByName(agentName, reportMap);
            if (res != null) {
            	if(res.containsKey("error")){
            		return success(ParamUtil.getString(res, "error", ""));
            	}
                Map insert = data2ReportLogMap(data, formBean, res);
                kkBaseFormManager.saveUnflowData(Constants.hehe, Constants.createUser, insert);
                return success("ok");
            }
        } catch (BusinessException e) {
            // TODO Auto-generated catch block
            LOG.error("##强生客开: ", e);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
        	LOG.error("##强生客开: ", e);
        }
        return success("发送生成启信宝定制报告异常!");
    }

    private Map data2ReportMap(FormDataMasterBean data, FormBean formBean) {
        Map map = new HashMap();
        map.put("公司名称", getString(data, formBean, "经销商名称"));
        Map fuzr = new HashMap();
        fuzr.put("姓名", getString(data, formBean, "公司负责人"));
        fuzr.put("手机", getString(data, formBean, "phone_公司负责人手机"));
        fuzr.put("电话", getString(data, formBean, "公司负责人电话"));
        fuzr.put("电子邮件", getString(data, formBean, "email_公司负责人电子邮件"));
        map.put("公司负责人", fuzr);
        Map yew = new HashMap();
        yew.put("姓名", getString(data, formBean, "业务联系人"));
        yew.put("手机", getString(data, formBean, "phone_业务联系人手机"));
        yew.put("电话", getString(data, formBean, "业务联系人电话"));
        yew.put("电子邮件", getString(data, formBean, "email_业务联系人电子邮件"));
        map.put("业务联系人", yew);
        Map fap = new HashMap();
        String fapiaoAdress = "";
        fapiaoAdress += getEnumDisplay(data, formBean, "发票邮件地址省") == null ? "" : getEnumDisplay(data, formBean, "发票邮件地址省");
        fapiaoAdress += getEnumDisplay(data, formBean, "发票邮件地址市") == null ? "" : getEnumDisplay(data, formBean, "发票邮件地址市");
        fapiaoAdress += getEnumDisplay(data, formBean, "发票邮件地址区") == null ? "" : getEnumDisplay(data, formBean, "发票邮件地址区");
        fapiaoAdress += getEnumDisplay(data, formBean, "发票邮件地址县") == null ? "" : getEnumDisplay(data, formBean, "发票邮件地址县");
        fap.put("邮寄地址", fapiaoAdress);
        fap.put("详细地址", getString(data, formBean, "发票邮件地址请填写详细地址街道楼牌号等"));
        fap.put("邮编", getString(data, formBean, "发票邮件地址邮编"));
        fap.put("电子邮件", getString(data, formBean, "email_发票邮寄地址电子邮件"));
        map.put("发票信息", fap);

        for (FormTableBean subTable : formBean.getSubTableBean()) {
            if (subTable.getDisplay().contains("公司基本信息")) {

            } else if (subTable.getDisplay().contains("订货信息")) {
                for (FormDataSubBean subData : data.getSubData(subTable.getTableName())) {
                    Map cangk = new HashMap();
                    String adress = "";
                    adress += getEnumDisplay(subData, formBean, "送货仓库地址_省") == null ? "" : getEnumDisplay(subData, formBean, "送货仓库地址_省");
                    adress += getEnumDisplay(subData, formBean, "送货仓库地址_市") == null ? "" : getEnumDisplay(subData, formBean, "送货仓库地址_市");
                    adress += getEnumDisplay(subData, formBean, "送货仓库地址_区") == null ? "" : getEnumDisplay(subData, formBean, "送货仓库地址_区");
                    adress += getEnumDisplay(subData, formBean, "送货仓库地址_县") == null ? "" : getEnumDisplay(subData, formBean, "送货仓库地址_县");
                    cangk.put("地址", adress + getString(subData, formBean, "送货仓库地址_详细地址"));
                    cangk.put("邮编", getString(subData, formBean, "送货仓库地址_邮编"));
                    map.put("送货仓库", cangk);
                }
            }
        }

        List members = new ArrayList();
        try {
            FormBean keyBean = formApi4Cap4.getFormByFormCode(Constants.keyMemberCode);
            List<FormDataMasterBean> keyMembers = kkBaseFormManager.findActiveKeyMember(formBean, data);
            for (FormDataMasterBean keyData : keyMembers) {
                Map member = new HashMap();
                member.put("姓名", getString(keyData, keyBean, "姓名"));
                member.put("职位", getString(keyData, keyBean, "职位"));
                member.put("出生年月", getTimeString(keyData, keyBean, "出生年月"));
                if(Strings.isNotEmpty(getString(keyData, keyBean, "OCR补充地址"))){
                	member.put("地址", getString(keyData, keyBean, "OCR补充地址"));
                } else {
                	member.put("地址", getString(keyData, keyBean, "OCR地址"));
                }
                if(Strings.isNotEmpty(getString(keyData, keyBean, "OCR补充性别"))){
                	member.put("性别", getString(keyData, keyBean, "OCR补充性别"));
                } else {
                	member.put("性别", getString(keyData, keyBean, "OCR性别"));
                }
                if(Strings.isNotEmpty(getString(keyData, keyBean, "OCR补充民族"))){
                	member.put("民族", getString(keyData, keyBean, "OCR补充民族"));
                } else {
                	member.put("民族", getString(keyData, keyBean, "OCR民族"));
                }
                if(Strings.isNotEmpty(getString(keyData, keyBean, "OCR补充身份证号"))){
                	member.put("身份证号", getString(keyData, keyBean, "OCR补充身份证号"));
                } else {
                	member.put("身份证号", getString(keyData, keyBean, "OCR身份证号"));
                }
                if(Strings.isNotEmpty(getString(keyData, keyBean, "OCR补充有效日期"))){
                	member.put("有效日期", getString(keyData, keyBean, "OCR补充有效日期"));
                } else {
                	member.put("有效日期", getString(keyData, keyBean, "OCR有效日期"));
                }
                if(Strings.isNotEmpty(getString(keyData, keyBean, "OCR补充签发机关"))){
                	member.put("签发机构", getString(keyData, keyBean, "OCR补充签发机关"));
                } else {
                	member.put("签发机构", getString(keyData, keyBean, "OCR签发机关"));
                }
                member.put("工作过的职位", getString(keyData, keyBean, "曾在政府机关或事业单位或医院工作过的职位"));
                member.put("所在省市及地址", getString(keyData, keyBean, "曾工作过的医院所在省市及地址"));
                member.put("现全名", getString(keyData, keyBean, "曾任医院现全名"));
                member.put("关键人员姓名", getString(keyData, keyBean, "关键人员姓名"));

                for (FormTableBean subTable : keyBean.getSubTableBean()) {
                    if (subTable.getDisplay().contains("工作教育经历")) {
                        List<Map> list = new ArrayList<Map>();
                        FormDataMasterBean masterList2=formApi4Cap4.findDataById(keyData.getId(), keyBean.getId(), null);
                        LOG.info("ddkk:-------------"+masterList2.getId());
                        if (null != masterList2.getSubData(subTable.getTableName())) {
                            for (FormDataSubBean subData : masterList2.getSubData(subTable.getTableName())) {
                                Map jingl = new HashMap();
                                jingl.put("类型", getEnumDisplay(subData, keyBean, "类型"));
                                jingl.put("起始年月", getTimeString(subData, keyBean, "工作教育经历起始年月"));
                                if ("至今".equals(getEnumDisplay(subData, keyBean, "是否至今"))) {
                                    jingl.put("终止年月", null);
                                } else {
                                    jingl.put("终止年月", getTimeString(subData, keyBean, "工作教育金额终止年月"));
                                }
                                jingl.put("学校或单位名称", getString(subData, keyBean, "学校及单位名称"));
                                jingl.put("专业或职位", getString(subData, keyBean, "专业或职位"));
                                jingl.put("学籍描述或工作性质", getEnumDisplay(subData, keyBean, "学籍描述或工作性质"));
                                jingl.put("备注", getString(subData, keyBean, "备注"));
                                list.add(jingl);
                            }
                        }
                        member.put("工作教育经历", list);
                    } else if (subTable.getDisplay().contains("其他相关经历")) {
                        List<Map> list2 = new ArrayList<Map>();
                        if (null != keyData.getSubData(subTable.getTableName())) {
                        	FormDataMasterBean masterList2=formApi4Cap4.findDataById(keyData.getId(), keyBean.getId(), null);
                            for (FormDataSubBean subData : masterList2.getSubData(subTable.getTableName())) {
                                Map jingl2 = new HashMap();
                                jingl2.put("起始年月", getTimeString(subData, keyBean, "其他相关经历起始年月"));
                                if ("至今".equals(getEnumDisplay(subData, keyBean, "其他相关经历是否至今"))) {
                                    jingl2.put("终止年月", null);
                                } else {
                                    jingl2.put("终止年月", getTimeString(subData, keyBean, "其他相关经历终止年月"));
                                }
                                jingl2.put("组织名称", getString(subData, keyBean, "组织名称"));
                                jingl2.put("担任职务", getString(subData, keyBean, "担任职务"));
                                list2.add(jingl2);
                            }
                        }
                        member.put("其他相关经历", list2);
                    }
                }
                members.add(member);
            }
        } catch (BusinessException e) {
            // TODO Auto-generated catch block
            LOG.error("##强生客开: ", e);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
        	LOG.error("##强生客开: ", e);
        }
        Map reportMap = new HashMap();
        reportMap.put("企业信息", map);
        reportMap.put("关键人员信息", members);
        return reportMap;
    }

    private Map data2ReportLogMap(FormDataMasterBean data, FormBean formBean, Map param) {
        Map logMap = new HashMap();
        logMap.put("报告ID", ParamUtil.getString(param, "id"));
        logMap.put("流水号", data.getFieldValue(formBean.getFieldBeanByDisplay("经销商ID").getName()));
        logMap.put("经销商名称", data.getFieldValue(formBean.getFieldBeanByDisplay("经销商名称").getName()));
        logMap.put("节点处理人", AppContext.currentUserId());
        return logMap;
    }

    private String getString(FormDataMasterBean formDataMasterBean, FormBean formBean, String display) {
        try {
            return formDataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay(display).getName()).toString();
        } catch (Exception e) {
            return "";
        }
    }

    private String getString(FormDataSubBean formDataMasterBean, FormBean formBean, String display) {
        try {
            return formDataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay(display).getName()).toString();
        } catch (Exception e) {
            return "";
        }
    }

    private String getTimeString(FormDataMasterBean formDataMasterBean, FormBean keyBean, String display) {
        try {
            return DateUtil.format((Date) formDataMasterBean.getFieldValue(keyBean.getFieldBeanByDisplay(display).getName()),
                    "yyyy-MM-dd");// HH:mm:ss
        } catch (Exception e) {
            return "";
        }
    }

    private String getTimeString(FormDataSubBean formDataMasterBean, FormBean keyBean, String display) {
        try {
            return DateUtil.format((Date) formDataMasterBean.getFieldValue(keyBean.getFieldBeanByDisplay(display).getName()),
                    "yyyy-MM-dd");// HH:mm:ss
        } catch (Exception e) {
            return "";
        }
    }

    private String getEnumDisplay(FormDataSubBean formDataMasterBean, FormBean keyBean, String display) {
        try {
            Object obj = formDataMasterBean.getFieldValue(keyBean.getFieldBeanByDisplay(display).getName());
            return keyBean.getFieldBeanByDisplay(display).getDisplayValue(obj, true)[1].toString();
        } catch (Exception e) {
            return "";
        }
    }

    private String getEnumDisplay(FormDataMasterBean formDataMasterBean, FormBean keyBean, String display) {
        try {
            Object obj = formDataMasterBean.getFieldValue(keyBean.getFieldBeanByDisplay(display).getName());
            return keyBean.getFieldBeanByDisplay(display).getDisplayValue(obj, true)[1].toString();
        } catch (Exception e) {
            return "";
        }
    }

}
